
/*
 * 文件名：AESUntils.java 版权：Copyright by www.rsrtech.net 描述： 修改人：郑净云 修改时间：2017年7月27日
 */

package com.snailhd.common.util.base;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class AESUtil {


	private static final String KEY = "djfjsd1aAhd92s.hs,djd@^&";


	public static String encry(String text ) throws Exception{
		return encry(text,KEY);
	}


	/**
	 * 加密 AES-->Base64
	 * 
	 * @param text 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encry(String text, String key) throws Exception {
		byte[] byteText = text.getBytes("utf-8");
		byte[] byte_cipher = aesOpt(byteText, key, Cipher.ENCRYPT_MODE);
		return base64Encry(byte_cipher).replace("\n", "").replace("\r", "");
	}


	public static String decry(String ciphertext) throws Exception {
		return decry(ciphertext, KEY);
	}

	/**
	 * 解密 base64-->AES
	 * 
	 * @param ciphertext
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decry(String ciphertext, String key) throws Exception {
		byte[] byte_cipher = base64Decry(ciphertext);
		byte[] byte_text = AESUtil.aesOpt(byte_cipher, key, Cipher.DECRYPT_MODE);
		return new String(byte_text, "utf-8");
	}

	/**
	 * aes 加密解密 
	 * @param params
	 * @param key 
	 * @param mode: Cipher.ENCRYPT_MODE， Cipher.DECRYPT_MODE
	 * @return
	 * @throws Exception
	 */
	private static byte[] aesOpt(byte[] params, String key, int mode) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(key.getBytes());
		kgen.init(128, secureRandom);
		SecretKey secretKey = kgen.generateKey();// 根据用户密码，生成一个密钥
		byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
		SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
		Cipher cipher = Cipher.getInstance("AES");// 创建密码器
		cipher.init(mode, secretKeySpec);// 初始化为解密模式的密码器
		return cipher.doFinal(params);
	}

	/**
	 * base64加密
	 * @param params
	 * @return
	 */
	public static String base64Encry(byte[] params) {
		return new BASE64Encoder().encode(params);
	}

	/**
	 * base64解密
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static byte[] base64Decry(String params) throws Exception {
		return new BASE64Decoder().decodeBuffer(params);

	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

//	public static void main(String[] args) throws Exception {
//		String password = "35635537hbsdj83ebb";
//		String text = "{ \"loginid\": \"462617762796142592\",\"userid\": \"018e6c542282374413\"}";
//
//		long b = System.currentTimeMillis();
//		String bs = AESUtil.encry(text, password);
//		System.out.println(bs.replace("\n", ""));
////		bs = "R4iekuhbmy211eCrdSw982cErBFAL2+Yr4U8pG7N73jhYn51he0kg/jofzZngD+oMaHFqeAHG1tFLuYvNXeBFA==";
//		String bs1 = AESUtil.decry(bs.replace("\n", ""), password);
//		System.out.println(bs1);
//		System.out.println(System.currentTimeMillis() - b);
//
//	}

}
